package com.lz.ionicbase.ui.activity;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Environment;
import android.support.design.widget.CoordinatorLayout;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.lz.ionicbase.R;
import com.lz.ionicbase.SuperApp;
import com.lz.ionicbase.engine.SetHelper;
import com.lz.ionicbase.ui.activity.action.ISetActivity;
import com.lz.ionicbase.utils.BaseUtil;
import com.lz.ionicbase.utils.Constant;
import com.lz.ionicbase.utils.DataCleanManager;
import com.lz.ionicbase.utils.SpUtils;
import com.lz.ionicbase.widget.Notice;

import java.io.File;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

import static android.app.DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED;


/**
 * Created by lenovo on 2017/2/17.
 */

public class SetActivity extends BaseActivity implements ISetActivity {

    @InjectView(R.id.coordinator)
    CoordinatorLayout coordinator;
    @InjectView(R.id.customTitle_tv)
    TextView customTitle_tv;
    @InjectView(R.id.language_rl)
    RelativeLayout language_rl;

    @InjectView(R.id.lan_list_ll)
    LinearLayout lan_list_ll;

    @InjectView(R.id.my_back)
    ImageView myBack;

    @InjectView(R.id.set_cache_tv)
    TextView set_cache_tv;

    @InjectView(R.id.language_tv)
    TextView language_tv;
    @InjectView(R.id.lan_zh_bt)
    TextView lan_zh_bt;
    @InjectView(R.id.lan_en_bt)
    TextView lan_en_bt;

    @InjectView(R.id.down_arrow_iv)
    ImageView down_arrow_iv;

    @InjectView(R.id.notice_switch)
    Switch notice_switch;

    private Context context;


    private static final String apkPath = "LZ_SuperApp";
    private static final String apkName = "superapp.apk";


    private SetHelper setHelper;

    private Map<String, Object[]> lanMap = SuperApp.lanMap;

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                Log.v("SetActivity", "action = " + action);
             /*
             * 获取下载完成对应的下载ID, 这里下载完成指的不是下载成功, 下载失败也算是下载完成,
             * 所以接收到下载完成广播后, 还需要根据 id 手动查询对应下载请求的成功与失败.
             */
                long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1L);
                if (id == downloadId) {
                    String path = "/" + apkPath + "/" + apkName;
                    String filePath = Environment.getExternalStorageDirectory() + path;
                    Intent install = new Intent(Intent.ACTION_VIEW);
//                    Intent install = new Intent(Intent.ACTION_INSTALL_PACKAGE);
                    install.setDataAndType(Uri.fromFile(new File(filePath)), "application/vnd.android.package-archive");
                    startActivity(install);
                }
            }
        }
    };
    private long downloadId;

    @Override
    protected int getActivityLayout() {
        return R.layout.activity_myset;
    }

    @Override
    protected void initView() {
        context = this;
        ButterKnife.inject(this);

        customTitle_tv.setText(R.string.settings);

        try {
            String totalCacheSize = DataCleanManager.getTotalCacheSize(context);
            set_cache_tv.setText(totalCacheSize);
        } catch (Exception e) {
            e.printStackTrace();
        }

        boolean isNotice = SpUtils.getBoolean(context, SpUtils.KEY_RECEIVE_NOTICE, true);
        notice_switch.setChecked(isNotice);

        //显示当前语言设置
        showCurrentLan();

        setHelper = new SetHelper(SetActivity.this);
        registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }

    private void showCurrentLan() {
        String spLanguage = SpUtils.getString(getApplicationContext(),
                SpUtils.KEY_LANGUAGE, "简体中文");

        language_tv.setText(spLanguage);

        for (int i = 0; i < lan_list_ll.getChildCount(); i++) {
            TextView tv = (TextView) lan_list_ll.getChildAt(i);
            if (spLanguage.equals(tv.getText().toString())) {
                tv.setBackgroundColor(0X4D9B9A9B);
                selectedView = tv;
                return;
            }
        }
    }

    @Override
    protected void initListener() {
        notice_switch.setOnCheckedChangeListener(switchChangeListener);
    }


    //销毁子线程,销毁广播接收者
    @Override
    protected void onDestroy() {
        super.onDestroy();
        setHelper.onDestroy();
        unregisterReceiver(receiver);
    }


    @OnClick({R.id.my_back, R.id.modify_sAddress_rl, R.id.cleanCache_rl, R.id.language_rl,
            R.id.lan_zh_bt, R.id.lan_en_bt, R.id.set_cache_tv, R.id.checkUpgrade_rl,
            R.id.exit_login_bt, R.id.feedBack_rl})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.my_back:
                finish();
                break;
            case R.id.language_rl:
                changeArrowState();
                break;
            case R.id.lan_zh_bt:
                changeLanState((TextView) view);
                break;
            case R.id.lan_en_bt:
                changeLanState((TextView) view);
                break;
            case R.id.modify_sAddress_rl:
                startActivity(new Intent(getApplicationContext(), SetServerActivity.class));
                break;
            case R.id.cleanCache_rl:
                cleanCach();
                break;
            case R.id.checkUpgrade_rl:
                checkUpgrade();
                break;
            case R.id.feedBack_rl:
                startActivity(new Intent(getApplicationContext(), FeedBackActivity.class));
                break;
            case R.id.exit_login_bt:
                exitLogin();
                break;
            default:
                break;
        }
    }

    private void exitLogin() {
        SuperApp.removeAppCookie();
        SpUtils.saveBoolean(context, Constant.ISAUTO, false);

        Intent intent = new Intent(this, WelcomeActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    private void checkUpgrade() {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String deviceId = telephonyManager.getDeviceId();
        String token = SpUtils.getString(context, Constant.TOKEN, "");
        String versionName = SuperApp.getAppVersionName(context);

        Map<String, String> param = new HashMap();
        param.put("uid", deviceId);
        param.put("token", token);
        param.put("version", BaseUtil.getBase64(versionName));

        String baseUrl = SpUtils.getString(context, SpUtils.KEY_BASE_URL, "");
        String url = baseUrl + Constant.CHECK_UPGRADE;
        setHelper.checkUpgrade(url, param);
    }

    private boolean isOpened = false;

    private void changeArrowState() {
        if (isOpened) {
            down_arrow_iv.setBackgroundResource(R.mipmap.down_arrow);
            lan_list_ll.setVisibility(View.GONE);
        } else {
            down_arrow_iv.setBackgroundResource(R.mipmap.down_arrow_selected);
            lan_list_ll.setVisibility(View.VISIBLE);
        }
        isOpened = !isOpened;
    }

    private TextView selectedView;

    private void changeLanState(TextView textView) {
        if (selectedView == textView) return;

        textView.setBackgroundColor(0X4D9B9A9B);
        selectedView.setBackgroundColor(0XFFF8F8F8);
        selectedView = textView;

        String lan = textView.getText().toString().trim();
        language_tv.setText(lan);
        setLanguage(lan);
    }

    private void setLanguage(String language) {
        Resources resources = getApplicationContext().getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        Configuration config = resources.getConfiguration();
        // 应用用户选择语言
        config.locale = (Locale) lanMap.get(language)[1];

        Log.e("setLanguage", config.locale.getLanguage());

        resources.updateConfiguration(config, dm);

        SpUtils.saveString(getApplicationContext(), SpUtils.KEY_LANGUAGE, language);

        Intent intent = new Intent(getApplication(), LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);

//        android.os.Process.killProcess(android.os.Process.myPid());
//        System.exit(0);
    }

    private void cleanCach() {
        Notice.alert(context, "确定清理缓存?", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
//                SharedPreferencesUtils.clear(SetActivity.this);
                DataCleanManager.clearAllCache(context);
                Toast.makeText(context, "已清理", Toast.LENGTH_SHORT).show();
                set_cache_tv.setText("0B");
            }
        });

    }


    private CompoundButton.OnCheckedChangeListener switchChangeListener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            String deviceId = telephonyManager.getDeviceId();
            String token = SpUtils.getString(context, Constant.TOKEN, "");
            Map<String, String> param = new HashMap();
            param.put("uid", deviceId);
            param.put("token", token);
            param.put("ifSend", isChecked ? "1" : "0");

            String baseUrl = SpUtils.getString(context, SpUtils.KEY_BASE_URL, "");
            String url = baseUrl + Constant.IS_SEND_MSG;
            setHelper.setIsNotice(url, param);
            notice_switch.setEnabled(false);
        }
    };

    @Override
    public void onSaveIsNoticeSuccess() {
        notice_switch.setEnabled(true);
        String msg = "已关闭消息提醒!";
        if(notice_switch.isChecked()){
            msg = "已打开消息提醒!";
        }
        Notice.showSnackbar(context, coordinator, msg);
        SpUtils.saveBoolean(context, SpUtils.KEY_RECEIVE_NOTICE, notice_switch.isChecked());
    }

    @Override
    public void onSaveIsNoticeError(Exception e) {
        notice_switch.setEnabled(true);
        notice_switch.setOnCheckedChangeListener(null);//防死循环
        notice_switch.toggle();
        notice_switch.setOnCheckedChangeListener(switchChangeListener);

    }

    @Override
    public void onNeedUpgrade(String url) {
        String baseUrl = SpUtils.getString(context, SpUtils.KEY_BASE_URL, "");
        url = baseUrl + url;

        DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        //创建一个Request对象
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));

        request.allowScanningByMediaScanner();
        request.setMimeType("application/vnd.android.package-archive");
        request.setNotificationVisibility(VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//        request.setTitle("");

        //设置下载文件路径
        request.setDestinationInExternalPublicDir(apkPath, apkName);

        //删除同名文件
        String path = "/" + apkPath + "/" + apkName;
        String filePath = Environment.getExternalStorageDirectory() + path;
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
        }
        //开始下载
        downloadId = downloadManager.enqueue(request);

        Toast.makeText(context, "正在下载!", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onLastVersion() {
        Notice.showSnackbar(context, coordinator,"已经是最新版本！");
    }

    @Override
    public void onDataException() {
        Notice.dataException(context);
    }

}
